Imports System.Threading

Module MonitorTryEnter

    Public Buffer As Integer
    Public BufferEmpty As Boolean = True
    Public MonitorLock As Object = New Object()

    Sub Producer()
        Dim Value As Integer = 0
        Do
            If (Monitor.TryEnter(MonitorLock)) Then
                If (BufferEmpty) Then
                    BufferEmpty = False
                    Buffer = Value

                    If (Value = 0) Then
                        Value = 1
                    Else
                        Value = 0
                    End If
                    Console.WriteLine()
                    Console.WriteLine("Producer: " & Buffer)
                End If
                Monitor.Exit(MonitorLock)
            Else
                Console.Write("P")
            End If
        Loop While (True)
    End Sub

    Sub Consumer()
        Dim Value As Integer
        Do
            If (Monitor.TryEnter(MonitorLock)) Then
                If (Not BufferEmpty) Then
                    BufferEmpty = True
                    Thread.CurrentThread.Sleep(10)

                    Value = Buffer
                    Console.WriteLine()
                    Console.WriteLine("Consumer: " & Value)
                End If
                Monitor.Exit(MonitorLock)
            Else
                Console.Write("C")
            End If
        Loop While (True)
    End Sub

    Sub Main()
        Dim ProducerThread As Thread
        Dim ConsumerThread As Thread

        ProducerThread = New Thread(AddressOf Producer)
        ConsumerThread = New Thread(AddressOf Consumer)

        ProducerThread.Start()
        ConsumerThread.Start()
    End Sub
End Module
